#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 50 //最大队列长度
#define OK 1
#define ERROR 0
typedef int QElemType;

typedef struct
{
    QElemType *base; //存储空间基址
    int front;
    int rear;
} SeqQueue;

SeqQueue *InitQueue()
{
    SeqQueue *Q;
    Q = (SeqQueue *)malloc(MAXSIZE * sizeof(QElemType));
    Q->base = (QElemType *)malloc(MAXSIZE * sizeof(QElemType));
    if (!Q->base)
        return ERROR;
    Q->front = Q->rear = 0;
    return Q;
}

int EnQueue(SeqQueue *Q, QElemType e)
{
    //判断队列满
    if ((Q->rear + 1) % MAXSIZE == Q->front)
        return ERROR;
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear + 1) % MAXSIZE;
    return OK;
}

int DeQueue(SeqQueue *Q, QElemType *e)
{
    if (Q->front == Q->rear)
        return ERROR;
    //出队
    *e = Q->base[Q->front];
    Q->front = (Q->front + 1) % MAXSIZE;
    return OK;
}

int QueueLength(SeqQueue *Q)
{
    return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}

void QueueTraverse(SeqQueue *Q)
{
    int i;
    int length;
    i = 0;
    length = QueueLength(Q);
    while (i < length)
    {
        printf("%d ", Q->base[(Q->front + i) % MAXSIZE]); //从头到尾依次打印Q中的每个元素
        i++;
    }
}

void main()
{
    int n, e, i;
    SeqQueue *q;
    q = InitQueue(); //初始化循环队列
    printf("该循环队列最多可存放%d个元素\n", MAXSIZE - 1);
    printf("请输入数据元素的个数\n");
    scanf("%d", &n);
    printf("\n请输入%d个整数\n", n);
    for (i = 1; i <= n; i++)
    {
        scanf("%d", &e);
        EnQueue(q, e); //入队
    }
    printf("队列元素为：");
    QueueTraverse(q); //输出循环队列q的内容
    fflush(stdin);    //刷新缓冲区
    printf("\n请输入入队元素:");
    scanf("%d", &e);
    EnQueue(q, e);
    printf("队列更新：");
    QueueTraverse(q);
    fflush(stdin); //刷新缓冲区
    printf("\n\n执行出队操作\n");
    DeQueue(q, &e);             //出队
    printf("出队元素:%d\n", e); //输出出队元素值
    printf("队列更新：");
    QueueTraverse(q);
}
